<?php

namespace app\admin\model;

class OauthIntegral extends \app\common\model\OauthIntegral
{
    /**
     * 列表
     * @param $oauthId
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($oauthId, $where)
    {
        $sql = static::field('id, type, (after_num - before_num) AS integral, order_id, create_time')
            ->order(['create_time' => 'desc']);

        if ($where) {
            $sql->where($where);
        }

        // 积分总额
        $sumSql = static::field('SUM(after_num - before_num) AS integral')
            ->where('type', '<>', self::TYPE_BUY);

        $rest = 0;
        if ($oauthId > 0) {
            $sql->where(['oauth_id' => $oauthId]);

            // 积分总额
            $sumSql->where(['oauth_id' => $oauthId]);

            // 积分余额
            $oauth = Oauth::getOne($oauthId);
            if ($oauth) {
                $rest = $oauth['integral'];
            }
        }

        $orderIds = [];
        $data = $sql->paginate(null, false, ['query' => request()->param()]);
        foreach ($data->items() as $key => $value) {
            $orderIds[$value['order_id']] = $value['order_id'];
        }

        $class = [];
        if ($orderIds) {
            $class = OauthOrderClass::getClassByOrder($orderIds);
        }

        $model = $sql->paginate(null, false, ['query' => request()->param()])->each(function ($item, $key) use ($class) {
            $item['type'] = self::attributes('type', $item['type']);
            $item['className'] = isset($class[$item['order_id']]) ? implode(',', $class[$item['order_id']]) : '/';
            $item['create_time'] = get_datetime($item['create_time']);
            return $item;
        });

        $sum = $sumSql->select()->column('integral');

        // 获取总记录数
        $count = $model->total();
        return [
            'sum' => isset($sum[0]) ? $sum[0] : 0,
            'rest' => $rest,
            'model' => $model,
            'count' => $count
        ];
    }

    public static function sumIntegral($oauthIds)
    {
        return static::field('oauth_id, SUM(after_num - before_num) AS integral')
            ->where('type', '<>', self::TYPE_BUY)
            ->where('oauth_id', 'in', $oauthIds)
            ->group('oauth_id')
            ->select()
            ->column('integral', 'oauth_id');
    }
}